package com.steed.common.utils;

/**
 * Created by Tony on 17/7/24.
 */
public class DigitalTransUtils {

    private final static char[] mChars = "0123456789abcdef".toCharArray();

    /**
     * 数值字符串转ASCII码字符串,支持标准ASCII 和 ACSII扩展表
     * 数值范围 0-255,0x00-0xFF
     *
     * @param content 待转换内容
     * @param radix   进制
     * @return Ascii 编码的字符串
     */
    public static String digitStrToAsciiStr(String content, int radix) {
        try {
            int contentValue = Integer.parseInt(content, radix);
            if (contentValue > 255 || contentValue < 0)
                return content;
            return Character.toString((char) contentValue);
        } catch (NumberFormatException e) {
            return content;
        }
    }

    /**
     * 数值字符串数组转ASCII码字符串,支持标准ASCII 和 ACSII扩展表
     * 数值范围 0-255,0x00-0xFF
     *
     * @param content 数值字符串数组
     * @param radix   进制
     * @return ASCII码字符串
     */
    public static String digitArrStrToAsciiStr(String[] content, int radix) {
        StringBuilder converted = new StringBuilder("");
        if (null == content || content.length == 0)
            return null;
        for (String contentStr: content){
            String subValue = digitStrToAsciiStr(contentStr, radix);
            converted.append(subValue);
        }
        return converted.toString();
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param content 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String strToHexStr(String content) {
        if (null == content || content.isEmpty())
            return null;
        StringBuilder sb = new StringBuilder();
        byte[] bs = content.getBytes();
        for (byte contentByte : bs) {
            sb.append(mChars[(contentByte & 0xFF) >> 4]);
            sb.append(mChars[contentByte & 0x0F]);
            sb.append(" ");
        }
        return sb.toString().trim();
    }
}
